package com.yh.csx.test.auto;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@ConditionalOnProperty(name = "bsf.test.auto.sql.uri")
@ConditionalOnClass({Api.class})
@Api(tags = "自动化测试依赖接口")
public class AutoTestController {

  @Value("${bsf.test.auto.sql.uri}")
  private String queryUri;

  @Autowired
  private RestTemplateBuilder restTemplateBuilder;

  @PostMapping("bsf/test/sql/query")
  @ApiOperation("sql查询,from带上具体项目数据库名")
  public String sqlQuery(@RequestBody String sql) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> httpEntity = new HttpEntity<>(String.format("{\"sql\": \"%s\"}", sql),
        headers);
    return restTemplateBuilder.build()
        .postForObject(queryUri, httpEntity, String.class);
  }

  @GetMapping("bsf/test/sleep")
  @ApiOperation("休眠接口,时程序中断对应毫秒数")
  public void Sleep(@RequestParam int millisecond) throws InterruptedException {
    Thread.sleep(millisecond);
  }
}
